package creational_pattern.singleton.demo1;

import java.io.*;

// 测试序列化反序列化打破单例模式
public class Client {
    public static void main(String[] args) throws Exception {
        //writeObject2File();
        readObjectFromFile();
        readObjectFromFile();
    }

    // 像文件中写数据（对象）
    public static void writeObject2File() throws Exception {
        // 获取单例对象
        Singleton instance = Singleton.getInstance();
        // 创建对象输入流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\Java_Learning\\Design Mode\\Design_Mode\\src\\creational_pattern\\singleton\\demo1\\test.txt"));
        // 写对象
        oos.writeObject(instance);
        // 释放资源
        oos.close();
    }

    // 从文件读取数据（对象）
    public static void readObjectFromFile() throws Exception {
        // 创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\Java_Learning\\Design Mode\\Design_Mode\\src\\creational_pattern\\singleton\\demo1\\test.txt"));
        // 读取对象
        Singleton instance = (Singleton) ois.readObject();
        // 输入
        System.out.println(instance);
        // 释放资源
        ois.close();
    }
}
